package com.sk.weichat.ui.groupchat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.CommonRecyclerAdapter;
import com.sk.weichat.adapter.SelectContacts;
import com.sk.weichat.bean.EventSendVerifyMsg;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
* 最近联系人
* */
public class RecentContactsFragment extends EasyFragment {

    private RecyclerView recy_recent_contacts;
    private TextView empty;
    private CommonRecyclerAdapter mAdapter;
    private List<BaseSortModel<Friend>> mSortFriends = new ArrayList<>();
    private  List<String> mSelectPositions = new ArrayList<>();

    private String mLoginUserId;
    private Set<String> mExistIds = new HashSet<>();
    // 是否是通过单人聊天快速创建的群组
    private boolean mQuicklyCreate;
    //     快速建群时聊天对象的id与备注名/昵称
    private String mQuicklyId;
    private String mQuicklyName;

    private boolean isAltFriends;
    private List<String> mAltFriendList = new ArrayList<>();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mExistIds = ((TabSelectContactsActivity) activity).getExistIds();
        mSelectPositions =  ((TabSelectContactsActivity) activity).getSelectPositions();
        mQuicklyCreate = ((TabSelectContactsActivity) activity).isQuicklyCreate();
        mQuicklyId = ((TabSelectContactsActivity) activity).getQuicklyId();
        mQuicklyName = ((TabSelectContactsActivity) activity).getQuicklyName();

        isAltFriends = ((TabSelectContactsActivity) activity).isAltFriends();
        mAltFriendList = ((TabSelectContactsActivity) activity).getAltFriendList();
    }
    public static RecentContactsFragment getInstance() {
        RecentContactsFragment hf = new RecentContactsFragment();
        return hf;
    }
    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_recent_contacts;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        initView();
        loadData();
    }
    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView(){
        recy_recent_contacts = findViewById(R.id.recy_recent_contacts);
        empty = findViewById(R.id.empty);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_recent_contacts.setLayoutManager(manager);
        initListAdapter();
        mLoginUserId = coreManager.getSelf().getUserId();

    }

    private void loadData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(getActivity());
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            List<Friend> Allfriends=  FriendDao.getInstance().getNearlyMyFriendMsg(coreManager.getSelf().getUserId());
            Map<String, Integer> existMap = new HashMap<>();
            List<BaseSortModel<Friend>> sortedList;
            if (mExistIds!=null){
                sortedList = SortHelper.toSortedModelList(Allfriends, existMap, f -> {
                    if (isExist(f)) {
                        // 过滤掉已经在群里的，
                        return null;
                    } else {
                        return f.getShowName();
                    }
                });
            }else {
                sortedList = SortHelper.toSortedModelList(Allfriends, existMap, Friend::getShowName);
            }
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                if (mSortFriends != null) {
                    mSortFriends.clear();
                }
                for (int i=sortedList.size()-1;i>=0;i--){
                    if (!sortedList.get(i).getBean().getUserId().equals(Friend.ID_SYSTEM_MESSAGE)&!sortedList.get(i).getBean().getUserId().equals(Friend.ID_NEW_FRIEND_MESSAGE)){
                        mSortFriends.add(sortedList.get(i));
                    }
                }
                if (mSortFriends.size()==0){
                    empty.setVisibility(View.VISIBLE);
                    recy_recent_contacts.setVisibility(View.GONE);
                }else {
                    empty.setVisibility(View.GONE);
                    recy_recent_contacts.setVisibility(View.VISIBLE);
                }
                mAdapter.notifyDataSetChanged();
            });
        });
    }
    //初始化适配器及事件
    private void initListAdapter() {
        mAdapter = new CommonRecyclerAdapter(R.layout.row_select_contacts, mSortFriends) {
            @Override
            public void convert(BaseViewHolder holder, int position) {
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.user_name_tv);
                CheckBox check_box = holder.getView(R.id.check_box);


                Friend friend = mSortFriends.get(position).getBean();
                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getUserId(), avatar_img, true);
                }
                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : friend.getNickName());
                check_box.setChecked(false);
                if (friend.getStatus() == 100) {
                    check_box.setChecked(true);
                } else {
                    check_box.setChecked(false);
                }
                if (mQuicklyCreate) {
                    if (friend.getUserId().equals(mLoginUserId) || friend.getUserId().equals(mQuicklyId)) {
                        check_box.setChecked(true);
                    }
                }
            }
        };
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (isAltFriends){
                    if (mSelectPositions.size()>=10&&mSortFriends.get(position).getBean().getStatus()!=100){
                        ToastUtil.showToast(mActivity,"最多能@10个人");
                        return;
                    }
                }

                if (mSelectPositions.size()>=20&&mSortFriends.get(position).getBean().getStatus()!=100){
                    ToastUtil.showToast(mActivity,"一次只能选择20人");
                }else {
                    Friend friend = mSortFriends.get(position).bean;
                    if (mQuicklyCreate) {
                        if (friend.getUserId().equals(mLoginUserId)) {
                            ToastUtil.showToast(mActivity, getString(R.string.tip_cannot_remove_self));
                            return;
                        } else if (friend.getUserId().equals(mQuicklyId)) {
                            ToastUtil.showToast(mActivity, getString(R.string.tip_quickly_group_cannot_remove) + mQuicklyName);
                            return;
                        }
                    }
                    for (int i = 0; i < mSortFriends.size(); i++) {
                        if (mSortFriends.get(i).getBean().getUserId().equals(friend.getUserId())) {
                            if (friend.getStatus() != 100) {
                                friend.setStatus(100);
                                mSortFriends.get(i).getBean().setStatus(100);
                                SelectContacts contacts = new SelectContacts();
                                contacts.setUserId(friend.getUserId());
                                contacts.setSelect(true);
                                EventBus.getDefault().post(contacts);
                            } else {
                                friend.setStatus(101);
                                mSortFriends.get(i).getBean().setStatus(101);
                                SelectContacts contacts = new SelectContacts();
                                contacts.setUserId(friend.getUserId());
                                contacts.setSelect(false);
                                EventBus.getDefault().post(contacts);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }

            }
        });
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_recent_contacts.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        recy_recent_contacts.setAdapter(mAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(SelectContacts contacts) {
        for (int i = 0; i < mSortFriends.size(); i++) {

            if (mSortFriends.get(i).getBean().getUserId().equals(contacts.getUserId())){
                if (contacts.isSelect()){
                    mSortFriends.get(i).getBean().setStatus(100);
                }else {
                    mSortFriends.get(i).getBean().setStatus(101);
                }
            }
        }
            mAdapter.notifyDataSetChanged();
    }
    /**
     * 是否存在已经在那个房间的好友
     */
    private boolean isExist(Friend friend) {
        return mExistIds.contains(friend.getUserId());
    }
}
